package com.security.customer.access;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.util.Collection;

/**
 * @Author: TongRui乀
 * @Date: 2020-04-06 10:45
 * @description：  自定的权限认证
 */
@Slf4j
//@Component
public class CustomerDecideManager implements AccessDecisionManager {
    @Override
    public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> collection) throws AccessDeniedException, InsufficientAuthenticationException {

        if(authentication instanceof UserDetails){

            // 当前用户拥有的权限
            Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();

            log.info("当前资源需要的角色：{}， 当前用户拥有的角色：{}", StringUtils.join(authorities,","), StringUtils.join(collection, ","));

            // 几何求交集
            Collection intersection = CollectionUtils.intersection(authorities, collection);

            if(intersection.size() > 0){
                // 结束校验方法 继续向下执行
                return;
            }

        }

        // 如果没有交集 可能没有权限
        throw new AccessDeniedException("没有权限");

    }

    @Override
    public boolean supports(ConfigAttribute configAttribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
